//
//  ANIMController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/29.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANIMController.h"
#import "IMMessageCell.h"
#import "IMMessageReceiveCell.h"
#import "MessageInputView.h"
#import "IMMessageEntity.h"
#import "NSString+Random.h"
#import <CTAssetsPickerController.h>
#import "IMImageCellCell.h"
#import "IMImageReceiveCell.h"

@interface ANIMController ()<UITableViewDelegate,UITableViewDataSource,MessageInputViewDelegate,CTAssetsPickerControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MessageInputView *inputView;

@property (nonatomic, strong) NSMutableArray<IMMessageEntity *> *dataSource;

@end

@implementation ANIMController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = @"联系卖家";
    self.view.backgroundColor = kColorF2F2F2;
    
//    self.pageNo = 1;
    self.dataSource = @[].mutableCopy;
    
    [self requestHistory];
    
    [self readRequest];
    
    // 极光自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification
{
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
   
//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
//    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段，key 是自己定义的
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    if ([message.allKeys containsObject:@"pushType"] && [message[@"pushType"] intValue] == 2) {
        NSLog(@"收到消息：%@",content);
        // 添加消息到数据源
        IMMessageEntity *messageEntity = [IMMessageEntity yy_modelWithDictionary:message];
        messageEntity.type = @"2";
        [self.dataSource addObject:messageEntity];
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:MAX(0, self.dataSource.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        
        [self readRequest];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

- (NSString *)messageSource
{
    if ([self.orgId isEqualToString:kKefuId]) {
        return @"2";
    }
    return @"1";
}

- (void)requestHistory
{
    if (self.orgId == nil || self.orgId.length == 0) {
        return;
    }
    IMMessageEntity *message = self.dataSource.firstObject;
    NSDictionary *body = @{
                           @"chatRecordId":StringNone(message.chatRecordId),
                           @"pageSize":@20,
                           @"memberId":UserUtils.shared.vipId,
                           @"consumerId":self.orgId,
                           @"messageSource":[self messageSource]
                           };
    [URLManager.shareManager getUrlStr:Api_IM_History parameters:body entityClass:[IMMessageEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {

                NSArray<IMMessageEntity *> *messages = baseEntity.data;
                if (messages.count) {
                    NSMutableArray *temp = @[].mutableCopy;
                    [temp addObjectsFromArray:messages];
                    [temp addObjectsFromArray:self.dataSource];
                    self.dataSource = temp.mutableCopy;
                    [self.tableView reloadData];
                    if (message.chatRecordId) {
                        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:messages.count inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
                    }
                    else {
                        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:MAX(0, self.dataSource.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                    }
                    
                    if (messages.count >= 20) {
//                        self.pageNo++;
                    }
                    else {
                        self.tableView.mj_header.hidden = YES;
                    }
                    
                }
                else {
                    self.tableView.mj_header.hidden = YES;
                }
                [self.tableView.mj_header endRefreshing];
            }
            else {
                [MBProgressHUD showError:baseEntity.message];
                [self.tableView.mj_header endRefreshing];
            }
        }
        else {
            [self.tableView.mj_header endRefreshing];
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)readRequest
{
    NSDictionary *body = @{
                           @"memberId":UserUtils.shared.vipId,
                           @"consumerId":self.orgId,
                           @"messageSource":[self messageSource]
                           };
    [URLManager.shareManager postUrlStr:Api_Read_Message parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        NSLog(@"消息已读");
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        
    }];
}

- (void)requestSendMessage:(IMMessageEntity *)message
{
    IMMessageEntity *currentEntity;
    NSIndexPath *indexPath;
    for (int i = 0; i < self.dataSource.count; i++) {
        IMMessageEntity *entity = self.dataSource[i];
        if ([entity.chatRecordId isEqualToString:message.chatRecordId]) {
            currentEntity = entity;
            indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        }
    }
    NSDictionary *body = @{
                           @"receiver":message.receiver,
                           @"content":message.content,
                           @"sender":message.sender,
                           @"messageSource":[self messageSource]
                           };
    [URLManager.shareManager postUrlStr:Api_IM_Send parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                currentEntity.isAnimation = NO;
                currentEntity.isShowReSend = NO;
            }
            else {
                currentEntity.isAnimation = NO;
                currentEntity.isShowReSend = YES;
            }
        }
        else {
            currentEntity.isAnimation = NO;
            currentEntity.isShowReSend = YES;
        }
        
        
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        currentEntity.isAnimation = NO;
        currentEntity.isShowReSend = YES;
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

- (void)requestImageMessage:(IMMessageEntity *)message
{
    NSDictionary *body = @{
                           @"receiver":message.receiver,
                           @"sender":message.sender,
                           @"messageSource":[self messageSource]
                           };
    [URLManager.shareManager uploadUrlStr:Api_IM_Image_Send images:@[message.image] parameters:body fileDataName:@"files" success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObj) {
        NSIndexPath *indexPath;
        for (int i = 0; i < self.dataSource.count; i++) {
            IMMessageEntity *entity = self.dataSource[i];
            if ([entity.chatRecordId isEqualToString:message.chatRecordId]) {
                
                indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                
                break;
            }
        }
        IMMessageEntity *entity = self.dataSource[indexPath.row];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                entity.isAnimation = NO;
                entity.isShowReSend = NO;
            }
            else {
                entity.isAnimation = NO;
                entity.isShowReSend = YES;
            }
        }
        else {
            entity.isAnimation = NO;
            entity.isShowReSend = YES;
        }
        
        
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSIndexPath *indexPath;
        for (int i = 0; i < self.dataSource.count; i++) {
            IMMessageEntity *entity = self.dataSource[i];
            if ([entity.chatRecordId isEqualToString:message.chatRecordId]) {
                
                indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                break;
            }
        }
        IMMessageEntity *entity = self.dataSource[indexPath.row];
        entity.isAnimation = NO;
        entity.isShowReSend = YES;
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

#pragma mark - MessageInputViewDelegate
// 点击加号
- (void)clickMoreFunction:(BOOL)enable
{
    if (enable) {
        [self.inputView showMoreFunctionView];
    }
    else {
        [self.inputView showKeyboard];
    }
}

- (void)clickEmojiFunction:(BOOL)enable
{
    if (enable) {
        [self.inputView showEmojiView];
    }
    else {
        [self.inputView showKeyboard];
    }
}

- (void)sendMessage:(NSString *)message
{
    IMMessageEntity *entity = [[IMMessageEntity alloc] init];
    entity.chatRecordId = [NSString randomString16];
    entity.sender = UserUtils.shared.vipId;
    entity.receiver = self.orgId;
    entity.content = message;
    entity.isAnimation = YES;
    entity.isShowReSend = NO;
    entity.type = @"1";
    entity.messageType = @"1";
    [self.dataSource addObject:entity];
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:MAX(0, self.dataSource.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    [self requestSendMessage:entity];
}

- (void)sendImageMessage:(NSArray *)imageMessage
{
    for (int i = 0; i < imageMessage.count; i++) {
        IMMessageEntity *entity = [[IMMessageEntity alloc] init];
        entity.chatRecordId = [NSString randomString16];
        entity.sender = UserUtils.shared.vipId;
        entity.receiver = self.orgId;
        entity.isAnimation = YES;
        entity.isShowReSend = NO;
        entity.type = @"1";
        entity.messageType = @"2";
        entity.image = imageMessage[i];
        [self.dataSource addObject:entity];
        [self requestImageMessage:entity];
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:MAX(0, self.dataSource.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        
    }
    
}

//- (void)keyboardWillShow:(CGFloat)keyboardHeight
//{
//    [UIView animateWithDuration:0.25 animations:^{
//        self.inputView.bottom = kScreenH-kStatusAndNavBarHeight-keyboardHeight;
//    }];
//}
//
//- (void)keyboardWillDismiss
//{
//    [UIView animateWithDuration:0.25 animations:^{
//        self.inputView.bottom = kScreenH-kStatusAndNavBarHeight;
//    }];
//}

- (void)messageInputViewDidChange:(CGFloat)minY
{
    if (self.dataSource.count >= 1) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:MAX(0, self.dataSource.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
    if (self.dataSource.count > 1) {
        // 获取对应cell的rect值（其值针对于UITableView而言）
        NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0];
        CGRect rect = [self.tableView rectForRowAtIndexPath:lastIndex];
        CGFloat lastMaxY = rect.origin.y + rect.size.height;
        //如果最后一个cell的最大Y值大于tableView的高度
        if (lastMaxY <= self.tableView.height) {
            if (lastMaxY >= minY) {
                self.tableView.top = minY - lastMaxY;
            } else {
                self.tableView.top = 0;
            }
        } else {
            self.tableView.top += (minY - self.tableView.bottom);
        }
    }
    
}

// 点击了相册
- (void)moreFunctionDidSelectedPhoto
{
    [self takeAlbum];
}

#pragma mark - privie

// 打开相册
- (void)takeAlbum
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        
        picker.showsSelectionIndex = YES;
        
        picker.delegate = self;
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            picker.modalPresentationStyle = UIModalPresentationFormSheet;
        }
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [window.rootViewController presentViewController:picker animated:YES completion:nil];
    });
}

- (void)setupSubViews
{
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, 0, kScreenW, kScreenH-kStatusAndNavBarHeight-56);
    [self.tableView registerClass:[IMMessageCell class] forCellReuseIdentifier:@"IMMessageCell"];
    [self.tableView registerClass:[IMMessageReceiveCell class] forCellReuseIdentifier:@"IMMessageReceiveCell"];
    [self.tableView registerClass:[IMImageCellCell class] forCellReuseIdentifier:@"IMImageCellCell"];
    [self.tableView registerClass:[IMImageReceiveCell class] forCellReuseIdentifier:@"IMImageReceiveCell"];
    
    self.inputView = [[MessageInputView alloc] initWithFrame:CGRectMake(0, kScreenH-kStatusAndNavBarHeight-kiPhoneXInsetBottom-56, kScreenW, 56)];
    self.inputView.delegate = self;
    [self.view addSubview:self.inputView];
    
    UITapGestureRecognizer *hideKey = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard:)];
    hideKey.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:hideKey];
}

- (void)hideKeyBoard:(UITapGestureRecognizer *)tap {
    
    [self.inputView hideAll];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMMessageEntity *message = self.dataSource[indexPath.row];
    if (message.messageType.intValue == 1) {// 文字消息
        if (message.type.intValue == 1) {
            IMMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IMMessageCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = message;
            WeakSelf
            cell.reSendHandle = ^(IMMessageEntity * _Nonnull message) {
                [weakSelf requestSendMessage:message];
            };
            return cell;
        }
        else {
            IMMessageReceiveCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IMMessageReceiveCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = message;
            return cell;
        }
    }
    else {// 图片消息
        if (message.type.intValue == 1) {
            IMImageCellCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IMImageCellCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = message;
            WeakSelf
            cell.reSendHandle = ^(IMMessageEntity * _Nonnull message) {
                [weakSelf requestImageMessage:message];
            };
            return cell;
        }
        else {
            IMImageReceiveCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IMImageReceiveCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.message = message;
            return cell;
        }
    }
    
    
}

#pragma mark - CTAssetsPickerControllerDelegate
//从相册选取图片后会调用该代理
-(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
    if (asset.mediaType != PHAssetMediaTypeImage)
    {
        [MBProgressHUD showMessage:@"只能上传照片"];
        return NO;
    }
    return YES;
}

// 在相册中选择图片后调用此代理
- (void)assetsPickerController:(CTAssetsPickerController *)picker didSelectAsset:(PHAsset *)asset
{
    
}

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets {
    //关闭相册界面
    [picker dismissViewControllerAnimated:YES completion:^{
        
        dispatch_group_t group = dispatch_group_create();
        dispatch_queue_t queue = dispatch_get_main_queue();
        NSMutableArray *items = @[].mutableCopy;
        for (int i = 0; i < assets.count; i++) {
            PHAsset *asset = assets[i];
            CGFloat scale = [UIScreen mainScreen].scale;
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            options.synchronous = YES;
            options.resizeMode = PHImageRequestOptionsResizeModeNone;
            CGSize size = CGSizeMake(asset.pixelWidth / scale, asset.pixelHeight / scale);
            dispatch_group_enter(group);
            dispatch_async(queue, ^{
                [[PHImageManager defaultManager] requestImageForAsset:asset
                                                           targetSize:size
                                                          contentMode:PHImageContentModeDefault
                                                              options:options
                                                        resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                            UIImage *img = result;
                                                            NSData *bigData = UIImagePNGRepresentation(result);
                                                            if (bigData.length > 500 * 1024) {
                                                                NSData *data = UIImageJPEGRepresentation(result, 500*1024.0/bigData.length);
                                                                img = [UIImage imageWithData:data];
                                                            }
                                                            
                                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                                [items addObject:img];
                                                            });
                                                            dispatch_group_leave(group);
                                                        }];
                
            });
        }
        dispatch_group_notify(group, queue, ^{
            // 发送图片消息
            [self sendImageMessage:items];
        });
        
    }];
    
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kColorF2F2F2;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 50;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        WeakSelf
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [weakSelf requestHistory];
        }];
        header.lastUpdatedTimeLabel.hidden = YES;
        [header setTitle:@"松开获取历史聊天记录" forState:MJRefreshStatePulling];
        [header setTitle:@"下拉获取历史聊天记录" forState:MJRefreshStateIdle];
        [header setTitle:@"正在获取记录中..." forState:MJRefreshStateRefreshing];
        _tableView.mj_header = header;
    }
    return _tableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
